package com.atosworldline.tfm.classLoader;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.FileInputStream;

public class DynamicClassLoader extends ClassLoader{

	public DynamicClassLoader(ClassLoader parent) {
		super(parent);
	}

		
	public Class loadClass(String pClass) throws ClassNotFoundException {
		if(pClass==null){return null;}	
		String packageName = pClass.substring(0,pClass.lastIndexOf("."));
		String className = pClass.substring(packageName.length()+1,pClass.length());

		return this.loadClass(packageName, className);
	}
	
	public Class loadClass(String packageName , String className) throws ClassNotFoundException {

		if(!"com.atosworldline.tfm.model".equals(packageName)){
			System.out.println("default class loader for package "+packageName+" class " +  className);
			return super.loadClass(packageName+"."+className);
		}else if("Document".equals(className)){
			return super.loadClass(packageName+"."+className);

		}else{

			try {
				String url = "./target/classes/com/atosworldline/tfm/model/"+className+".class";
				FileInputStream input = new FileInputStream(url);
				ByteArrayOutputStream buffer = new ByteArrayOutputStream();
				int data = input.read();

				while(data != -1){
					buffer.write(data);
					data = input.read();
				}

				input.close();

				byte[] classData = buffer.toByteArray();

				System.out.println("personnal class loader will redifin "+className+" with a total lenght of "+classData.length);
				return defineClass(packageName+"."+className,
						classData, 0, classData.length);

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace(); 
			}

			return null; 
		}
	}
}
